package com.jz.community.moduleshopping.goodsDetail.ui.view;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.bean.baseGoods.GoodInfo;
import com.jz.community.basecomm.bean.baseGoods.ShopInfo;
import com.jz.community.basecomm.bean.baseGoods.ShopListInfo;
import com.jz.community.basecomm.constant.ConstantErrorCode;
import com.jz.community.basecomm.task.GetGoodsSkuTask;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseImageLoaderUtils;
import com.jz.community.basecomm.utils.CharacterUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxTextTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.intentUtils.OrderIntentUtils;
import com.jz.community.commview.view.widget.FlowLayout;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.confirmOrder.bean.UpdateOrderCouponInfo;
import com.jz.community.moduleshopping.goodsDetail.bean.GoodsDetailInfo;
import com.jz.community.moduleshopping.goodsDetail.enums.GoodsAddCartType;
import com.jz.community.moduleshopping.goodsDetail.ui.GoodsDetailActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tony.Fan on 2018/3/29 09:29
 * <p>
 * 商品详情购物弹窗
 */
public class GoodsDetailAddCartPop extends PopupWindow implements View.OnClickListener {
    private ImageView ivCloseDialog, ivLogoDialog;
    private Button addBuyBtn, addCartBtn;
    private TextView tvGoodsPriceDialog, tvLimitNumDialog, tvReduceGoodsNum,
            tvGoodsNumDialog, tvAddGoodsNum, tvGoodsPricePreSell;
    private FlowLayout fl_title;
    private GoodsDetailActivity mContext;
    private GoodsDetailInfo mGoodsDetailInfo;
    private String goodsPrice;
    private String discountPrice;
    private int goodsFrom;
    private String stock;
    private String skuId;
    private String spidStr;
    private String shopId;
    private AddCartCallBackListener addCartCallBackListener;
    private String code; //卡包第三方支付码
    private int buyTimes; //限时购
    private String skuImage;

    public void setAddCartCallBackListener(AddCartCallBackListener addCartCallBackListener) {
        this.addCartCallBackListener = addCartCallBackListener;
    }

    public void setShowType(int showType) {
        showAddCartType(showType);
    }

    public void setBuyTimes(int buyTimes) {
        this.buyTimes = buyTimes;
    }

    public GoodsDetailAddCartPop(GoodsDetailActivity context) {
        this.mContext = context;
        View view = LayoutInflater.from(mContext).inflate(R.layout.module_shopping_choose_specification_or_repertory_dialog, null);
        initView(view);
    }

    public void addGoodsDetailInfo(GoodsDetailInfo goodsDetailInfo, String stock, String price, String discountPrice, String spStr, int goodsFrom) {
        this.mGoodsDetailInfo = goodsDetailInfo;
        this.goodsPrice = price;
        this.goodsFrom = goodsFrom;
        updateSpecTitleUI(spStr, false);
        showGoodsSkuAndPriceUI(stock, price, discountPrice);
    }

    private void initView(View view) {
        tvGoodsPriceDialog = view.findViewById(R.id.tv_goods_price_dialog);
        tvLimitNumDialog = view.findViewById(R.id.tv_limit_num_dialog);
        ivLogoDialog = view.findViewById(R.id.iv_logo_dialog);
        fl_title = view.findViewById(R.id.fl_title);
        tvReduceGoodsNum = view.findViewById(R.id.tv_reduce_goods_num);
        tvGoodsNumDialog = view.findViewById(R.id.tv_goods_num_dialog);
        tvAddGoodsNum = view.findViewById(R.id.tv_add_goods_num);
        tvGoodsPricePreSell = view.findViewById(R.id.tv_goods_price_pre_sell);
        ivCloseDialog = view.findViewById(R.id.iv_close_dialog);
        addBuyBtn = view.findViewById(R.id.add_buy_btn);
        addCartBtn = view.findViewById(R.id.add_cart_btn);
        tvGoodsNumDialog.setText("1");
        this.setOutsideTouchable(true);
        this.setContentView(view);
        this.setHeight(SHelper.getScreenH(mContext) * 2 / 3);
        this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        this.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(ContextCompat.getColor(mContext,R.color.transparent));
        this.setBackgroundDrawable(dw);
        this.setAnimationStyle(R.style.choose_repertory_anim);
        addListener();
    }

    /**
     * @param type
     */
    private void showAddCartType(int type) {
        switch (type) {
            case GoodsAddCartType.CART_TYPE_1:
                SHelper.vis(addBuyBtn, addCartBtn);
                break;
            case GoodsAddCartType.CART_TYPE_2:
                SHelper.vis(addBuyBtn);
                SHelper.gone(addCartBtn);
                break;
            case GoodsAddCartType.CART_TYPE_3:
                SHelper.gone(addBuyBtn);
                SHelper.vis(addCartBtn);
                break;
            case GoodsAddCartType.CART_TYPE_4:
                addBuyBtn.setText("立即兑换");
                SHelper.vis(addBuyBtn);
                SHelper.gone(addCartBtn);
                break;
            case GoodsAddCartType.CART_TYPE_5:
                buyGoodsTimes();
                break;
            case GoodsAddCartType.CART_TYPE_6:
                addBuyBtn.setText("已售罄");
                SHelper.vis(addBuyBtn);
                SHelper.gone(addCartBtn);
                showSkuBuyBtn(false, R.color.gray_light, R.color.gray_light);
                break;
        }
    }

    /**
     * 限时购开抢状态
     */
    private void buyGoodsTimes() {
        switch (buyTimes) {
            case 1:
                addBuyBtn.setText("即将开抢");
                SHelper.vis(addBuyBtn);
                SHelper.gone(addCartBtn);
                addBuyBtn.setBackgroundResource(R.color.gray_light);
                addBuyBtn.setEnabled(false);
                break;
            case 2:
                addBuyBtn.setText("活动结束");
                SHelper.vis(addBuyBtn);
                SHelper.gone(addCartBtn);
                addBuyBtn.setBackgroundResource(R.color.gray_light);
                addBuyBtn.setEnabled(false);
                break;
            case 3:
                addBuyBtn.setText("立即抢购");
                SHelper.vis(addBuyBtn);
                SHelper.gone(addCartBtn);
                break;
        }
    }


    //btn监听
    private void addListener() {
        tvReduceGoodsNum.setOnClickListener(this);
        tvAddGoodsNum.setOnClickListener(this);
        addCartBtn.setOnClickListener(this);
        addBuyBtn.setOnClickListener(this);
        ivCloseDialog.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_reduce_goods_num) {
            handleReduceGoodsNumClick();
        } else if (v.getId() == R.id.tv_add_goods_num) {
            handlePlusGoodsNumClick();
        } else if (v.getId() == R.id.add_cart_btn) {
            getGoodsSkuStatus(tvGoodsNumDialog.getText().toString().trim(), GoodsAddCartType.CART_TYPE_2);
        } else if (v.getId() == R.id.add_buy_btn) {
            getGoodsSkuStatus(tvGoodsNumDialog.getText().toString().trim(), GoodsAddCartType.CART_TYPE_3);
        } else if (v.getId() == R.id.iv_close_dialog) {
            dismiss();
        }
    }

    /**
     * 购买商品数量 - 操作
     */
    private void handleReduceGoodsNumClick() {
        int num = ConverterUtils.toInt(tvGoodsNumDialog.getText().toString().trim());
        if (num == 1) {
            num = 1;
        } else {
            num--;
        }
        tvGoodsNumDialog.setText(num + "");
    }

    /**
     * 购买商品数量 + 操作
     */
    private void handlePlusGoodsNumClick() {
        int num = ConverterUtils.toInt(tvGoodsNumDialog.getText().toString().trim());

        int max = ConverterUtils.toInt(stock);
        if (max >= num) {
            num++;
        } else {
            WpToast.l(mContext, "库存不足");
        }
        getGoodsSkuStatus(ConverterUtils.toString(num), GoodsAddCartType.CART_TYPE_1);
    }

    /**
     * 限购添加库存数量
     *
     * @param goodsNum
     */
    private void getGoodsSkuStatus(String goodsNum, int cartType) {
        new GetGoodsSkuTask(mContext, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                BaseResponseInfo baseResponseInfo = (BaseResponseInfo) o;
                if (!Preconditions.isNullOrEmpty(baseResponseInfo)) {
                    if (baseResponseInfo.getCode() == ConstantErrorCode.SUCC_CODE) {
                        handleAddCartAndBuyGoods(cartType, goodsNum);
                    } else {
                        WpToast.l(mContext, baseResponseInfo.getMessage());
                    }
                }
            }
        }).execute(mGoodsDetailInfo.getId(), goodsNum);
    }

    /**
     * 处理添加购物车、立即购买 库存状态
     *
     * @param cartType
     */
    private void handleAddCartAndBuyGoods(int cartType, String goodsNum) {
        switch (cartType) {
            case GoodsAddCartType.CART_TYPE_1:
                tvGoodsNumDialog.setText(goodsNum);
                break;
            case GoodsAddCartType.CART_TYPE_2:
                addCartCallBackListener.addCart(skuId, tvGoodsNumDialog.getText().toString().trim());
                break;
            case GoodsAddCartType.CART_TYPE_3:
                startToConfirmOrder(true);
                break;
        }
    }

    private void showGoodsImageUI(String skuImage) {
        if (Preconditions.isNullOrEmpty(skuImage)) {
            BaseImageLoaderUtils.getInstance().loadDefaltImage(mContext, ivLogoDialog, mGoodsDetailInfo.getImage().get(0));
        } else {
            BaseImageLoaderUtils.getInstance().loadDefaltImage(mContext, ivLogoDialog, skuImage);
        }
    }

    /**
     * 商品规格库存和价格
     *
     * @param stock
     * @param price
     */
    private void showGoodsSkuAndPriceUI(String stock, String price, String disCountPrice) {
        int sku = 0;

        if (!Preconditions.isNullOrEmpty(stock)) {
            sku = ConverterUtils.toInt(stock);
        }

        if (sku != 0) {
            tvLimitNumDialog.setText("库存充足");
            SHelper.vis(tvLimitNumDialog);
            if (mGoodsDetailInfo.getBuyType() != 3) {
                showSkuBuyBtn(true, R.drawable.btn_buy_shopping_btn, R.drawable.btn_add_shopping_cart_btn);
            }
        } else {
            SHelper.gone(tvLimitNumDialog);
            showSkuBuyBtn(false, R.color.gray_light, R.color.gray_light);
        }

        //规格商品价格
        if (!Preconditions.isNullOrEmpty(disCountPrice)) {
            tvGoodsPriceDialog.setText("¥" + CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(disCountPrice)));
            SHelper.vis(tvGoodsPriceDialog, tvGoodsPricePreSell);
            RxTextTool.getBuilder("").append(CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(price))).setStrikethrough().into(tvGoodsPricePreSell);
        } else {
            tvGoodsPriceDialog.setText("¥" + CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(price)));
            SHelper.vis(tvGoodsPriceDialog);
            SHelper.gone(tvGoodsPricePreSell);
        }
    }

    /**
     * 库存不足 显示状态调整
     *
     * @param isEnabled
     * @param btnBuyBg
     * @param btnCartBg
     */
    private void showSkuBuyBtn(boolean isEnabled, int btnBuyBg, int btnCartBg) {
        addBuyBtn.setEnabled(isEnabled);
        addCartBtn.setEnabled(isEnabled);
        addBuyBtn.setBackgroundResource(btnBuyBg);
        addCartBtn.setBackgroundResource(btnCartBg);
    }

    /**
     * 更新选中规格
     *
     * @param currentSpStr
     * @param isFirstLoad
     */
    private void updateSpecTitleUI(String currentSpStr, boolean isFirstLoad) {
        if (isFirstLoad) {
            fl_title.removeAllViews();
        }
        for (GoodsDetailInfo.SkuInfosBean itemInfo : mGoodsDetailInfo.getSkuInfos()) {
            Button bt;
            if (currentSpStr.equals(itemInfo.getSpStr())) {
                getGoodsSkuPropertiesMsg(itemInfo);
                bt = createButton(0, itemInfo.getSpStr());
            } else {
                bt = createButton(1, itemInfo.getSpStr());
            }
            if (!Preconditions.isNullOrEmpty(itemInfo.getSpStr())) {
                fl_title.addView(bt);
            }
        }
    }

    /**
     * @param selectType 0选中 1没选中
     * @return
     */
    private Button createButton(int selectType, String btnName) {
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, SHelper.dp2px(mContext, 25));
        lp.leftMargin = SHelper.dp2px(mContext, 5);
        lp.topMargin = SHelper.dp2px(mContext, 10);
        lp.bottomMargin = SHelper.dp2px(mContext, 10);
        Button bt = new Button(mContext);
        updateGoodsSpecSelected(bt, selectType);
        bt.setPadding(SHelper.dp2px(mContext, 5), 0, SHelper.dp2px(mContext, 5), 0);
        bt.setGravity(Gravity.CENTER);
        bt.setLayoutParams(lp);
        bt.setTextSize(12);
        bt.setText(btnName);
        return bt;
    }

    /**
     * 更新商品规格选中状态
     *
     * @param bt
     * @param selectType
     */
    private void updateGoodsSpecSelected(Button bt, int selectType) {
        if (selectType == 0) { //选中
            bt.setBackgroundResource(R.drawable.tv_border_gt);
            bt.setTextColor(mContext.getResources().getColor(R.color.white));
            bt.setOnClickListener(
                    new SizeColorOnclickListener(true));
            mContext.updateGoodsSkuProperties(spidStr);
        }

        if (selectType == 1) { //不选中
            bt.setBackgroundResource(R.drawable.bg_gray_light_no_bolder_radius);
            bt.setTextColor(mContext.getResources().getColor(R.color.balck));
            bt.setOnClickListener(
                    new SizeColorOnclickListener(false));
        }
    }

    public class SizeColorOnclickListener implements View.OnClickListener {

        boolean buttonStatus;

        public SizeColorOnclickListener(boolean buttonStatus) {
            this.buttonStatus = buttonStatus;
        }

        @Override
        public void onClick(View v) {
            Button btn = (Button) v;
            if (!buttonStatus) {
                for (GoodsDetailInfo.SkuInfosBean itemInfo : mGoodsDetailInfo.getSkuInfos()) {
                    if (btn.getText().toString().trim().equals(itemInfo.getSpStr())) {
                        updateSpecTitleUI(itemInfo.getSpStr(), true);
                        handleGoodsSpecSkuAndPrice(itemInfo.getSpidStr(), itemInfo);
                        return;
                    }
                }
            }
        }
    }

    /**
     * 商品规格价格、库存
     */
    private void handleGoodsSpecSkuAndPrice(String spStr, GoodsDetailInfo.SkuInfosBean skuInfosBean) {
        for (GoodsDetailInfo.SkuPropertiesBean skuPropertiesBean : mGoodsDetailInfo.getSkuProperties()) {
            String skuPropertiesBeanIdid = skuPropertiesBean.getId();
            for (GoodsDetailInfo.SkuPropertiesBean.PropertyValuesBean propertyValuesBean : skuPropertiesBean.getPropertyValues()) {
                String propertyValuesBeanId = propertyValuesBean.getId();
                String skuStr = skuPropertiesBeanIdid + "|" + propertyValuesBeanId;
                tvGoodsNumDialog.setText("1");
                if (spStr.equals(skuStr)) {
                    getGoodsSkuPropertiesMsg(skuInfosBean);
                    showGoodsSkuAndPriceUI(skuInfosBean.getStock(), skuInfosBean.getPrice(), skuInfosBean.getDiscountPrice());
                }
            }
        }
    }

    /**
     * 获取商品规格库存、价格基本信息
     *
     * @param skuInfosBean
     */
    private void getGoodsSkuPropertiesMsg(GoodsDetailInfo.SkuInfosBean skuInfosBean) {
        spidStr = skuInfosBean.getSpStr();
        skuId = skuInfosBean.getId();
        code = skuInfosBean.getCode();
        stock = skuInfosBean.getStock();
        shopId = mGoodsDetailInfo.getShop().getId();
        skuImage = skuInfosBean.getIcon();
        showGoodsImageUI(skuImage);
        showGoodsPrice(skuInfosBean);
    }

    /**
     * 商品规格价格
     *
     * @param skuInfosBean
     */
    private void showGoodsPrice(GoodsDetailInfo.SkuInfosBean skuInfosBean) {
        if (!Preconditions.isNullOrEmpty(skuInfosBean.getDiscountPrice())) {
            discountPrice = ConverterUtils.toString(skuInfosBean.getDiscountPrice());
        } else {
            goodsPrice = ConverterUtils.toString(skuInfosBean.getPrice());
        }
    }

    /**
     * 跳转确认订单页
     */
    public void startToConfirmOrder(boolean isDismiss) {
        if (goodsFrom == 0) {
            OrderIntentUtils.startFromOrderActivity(confirmOrderList(), 0);
        } else {
            OrderIntentUtils.startFromOrderActivity(confirmOrderList());
        }
        if (isDismiss) {
            dismiss();
        }
    }

    private String confirmOrderList() {
        ArrayList<ShopListInfo> mShopList = new ArrayList<>();
        String goodsNum = tvGoodsNumDialog.getText().toString().trim();
        String catId = mGoodsDetailInfo.get_embedded().getCategory().getId();

        //店铺对象
        ShopInfo shopInfo = new ShopInfo();

        ShopListInfo shopListInfo = new ShopListInfo();

        shopListInfo.setShopName(mGoodsDetailInfo.getShop().getName());
        shopListInfo.setShopId(shopId);
        shopInfo.setCode(code);
        shopInfo.setCityCode(mGoodsDetailInfo.getCityCode());
        shopInfo.setGoodFrom(1);
        shopInfo.setSource(mGoodsDetailInfo.getSource());
        shopInfo.setSendType(mGoodsDetailInfo.getDistributionType());
        shopInfo.setPickupPoint(mGoodsDetailInfo.getPickupPoint());
        shopInfo.setBuyType(mGoodsDetailInfo.getBuyType());

        mShopList.add(shopListInfo);

        ArrayList<GoodInfo> mGoodsList = new ArrayList<>();
        //商品对象
        GoodInfo goodInfo = new GoodInfo();
        goodInfo.setId(mGoodsDetailInfo.getId());
        goodInfo.setSkuId(skuId);
        goodInfo.setNums(ConverterUtils.toInt(goodsNum));
        goodInfo.setSkuName(spidStr);
        goodInfo.setBuyType(mGoodsDetailInfo.getBuyType());
        goodInfo.setSource(mGoodsDetailInfo.getSource());
        goodInfo.setName(mGoodsDetailInfo.getTitle());
        goodInfo.setPrice(goodsPrice);
        goodInfo.setDisCountPrice(discountPrice);
        if (Preconditions.isNullOrEmpty(skuImage)) {
            goodInfo.setImg(mGoodsDetailInfo.getImage().get(0));
        } else {
            goodInfo.setImg(skuImage);
        }
        goodInfo.setCategoryId(catId);
        mGoodsList.add(goodInfo);
        shopListInfo.setGoodsList(mGoodsList);
        shopInfo.setShopList(mShopList);
        return JSON.toJSONString(shopInfo);
    }

    //添加购物车回调
    public interface AddCartCallBackListener {
        void addCart(String skuid, String num);
    }
}

